package tum0r.cryptology.encryption;

import tum0r.misc.StringUtils;

import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 工程: JavaTools<br>
 * 包: tum0r.cryptology.encryption<br>
 * 创建者: tum0r<br>
 * 创建时间: 2020/8/21 23:23<br>
 * <br>
 */
public class Hash {
    public final String MD2 = "md2";
    public final String MD5 = "md5";
    public final String SHA1 = "sha-1";
    public final String SHA224 = "sha-224";
    public final String SHA256 = "sha-256";
    public final String SHA384 = "sha-384";
    public final String SHA512 = "sha-512";

    public String encryption(String planText) throws NoSuchAlgorithmException {
        return encryption(planText, SHA256, Charset.defaultCharset());
    }

    public String encryption(String planText, String mode) throws NoSuchAlgorithmException {
        return encryption(planText, mode, Charset.defaultCharset());
    }

    public String encryption(String planText, Charset charset) throws NoSuchAlgorithmException {
        return encryption(planText, SHA256, charset);
    }

    public String encryption(String planText, String mode, Charset charset) throws NoSuchAlgorithmException {
        StringBuilder result = new StringBuilder();
        mode = StringUtils.isNullOrEmpty(mode) ? SHA256 : mode;
        charset = charset == null ? Charset.defaultCharset() : charset;
        if (planText != null) {
            MessageDigest messageDigest = MessageDigest.getInstance(mode);
            byte[] data = messageDigest.digest(planText.getBytes(charset));
            String hex;
            for (byte datum : data) {
                hex = Integer.toHexString(datum & 0xff);
                if (hex.length() == 1) {
                    result.append("0");
                }
                result.append(hex);
            }
        }
        return result.toString();
    }
}
